package dao;

import java.util.ArrayList;
import java.util.List;

import hibernate.HibernateUtil;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import dto.ClienteDTO;
import entities.ClienteEntity;
import entities.EmpresaEntity;
import entities.ParticularEntity;

public class ClienteDAO {

	private static ClienteDAO instancia = null;
	private static SessionFactory sf = null;
	
	private ClienteDAO(){}
	
	public static ClienteDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new ClienteDAO();
		} 
		return instancia;
	}
	
	public boolean grabarCliente(ClienteEntity cliente)
	{
		try{
			Session session = sf.openSession();
			session.beginTransaction();
			session.persist(cliente);
			session.flush();
			session.getTransaction().commit();
			session.close();
			return true;
		}catch(Exception e)
		{
			return false;
		}
	}
	
	public void actualizarCliente(ClienteEntity cliente){
		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(cliente);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}

	public ClienteEntity LoadCliente(int id) 
	{
		Session session = sf.openSession();
		session.beginTransaction();
		ClienteEntity cli = (ClienteEntity) session.get(ClienteEntity.class, id);
		session.flush();
		session.getTransaction().commit();
		session.close();
		return cli;
	}

	public ParticularEntity getParticular(String dni) 
	{
		Session session = sf.openSession();
		session.beginTransaction();
		ParticularEntity p = (ParticularEntity) session.createQuery("from ParticularEntity p where p.DNI = :dni").setString("dni", dni).uniqueResult();
		session.flush();
		session.getTransaction().commit();
		session.close();
		return p;
	}

	public List<ParticularEntity> getParticularList() 
	{
		Session session = sf.openSession();
		session.beginTransaction();
		List<ParticularEntity> lista = session.createQuery("from ParticularEntity p").list();
		session.flush();
		session.getTransaction().commit();
		session.close();
		return lista;
	}
	
	public void grabarParticular(ParticularEntity particular){
		Session session = sf.openSession();
		session.beginTransaction();
		session.persist(particular);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
}

